import os
import uuid
import subprocess
import threading
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

# 外网访问端口
NET_PORT = 3002
# docker 容器内部端口
CONTAINER_PORT = 5000

SCRIPT_HISTORY_DIR = 'script_history'

# 确保目录存在
os.makedirs(SCRIPT_HISTORY_DIR, exist_ok=True)

def run_code(task_id, code, output, error):
    task_dir = os.path.join(SCRIPT_HISTORY_DIR, task_id)
    main_script_path = os.path.join(task_dir, 'main.py')

    with open(main_script_path, 'w', encoding='utf-8') as f:
        # 添加编码声明
        f.write("# -*- coding: utf-8 -*-\n")
        f.write(code)

    try:
        # 设置工作目录为任务文件夹
        result = subprocess.run(['python', 'main.py'], capture_output=True, text=True, timeout=10, cwd=task_dir)
        output.append(result.stdout)
        error.append(result.stderr)
    except subprocess.TimeoutExpired:
        error.append("Error: Code execution timed out.")
    except Exception as e:
        error.append(str(e))

@app.route('/execute', methods=['POST'])
def execute_code():
    data = request.json
    code = data.get('code')

    if not code or not isinstance(code, str):
        return jsonify({'error': 'Invalid code parameter'}), 400

    # 生成新的唯一任务 ID
    task_id = str(uuid.uuid4())  # 生成唯一任务编号

    # 创建任务文件夹
    task_dir = os.path.join(SCRIPT_HISTORY_DIR, task_id)
    os.makedirs(task_dir, exist_ok=True)

    output = []
    error = []

    # 使用线程执行代码
    thread = threading.Thread(target=run_code, args=(task_id, code, output, error))
    thread.start()
    thread.join()  # 等待线程完成

    # 获取生成的文件路径
    directory_contents = os.listdir(task_dir)
    file_paths = [f"http://localhost:{NET_PORT}/script_history/{task_id}/{file}" for file in directory_contents]

    # 返回结果
    return jsonify({
        'out': ''.join(output).strip() or ''.join(error).strip(),
        'paths': file_paths
    })

@app.route('/script_history/<task_id>/<path:filename>', methods=['GET'])
def serve_file(task_id, filename):
    return send_from_directory(os.path.join(SCRIPT_HISTORY_DIR, task_id), filename)

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=CONTAINER_PORT, debug=False)
